import {
  getOperateDataTable
} from '../../api/statistics'
import {
  OPERATE_DATA_LIST,
  OPERATE_DATA_DATA_COUNT,
  OPERATE_DATA_CURRENT_ROW,
  OPERATE_DATA_HISTORY_DATA,
  OPERATE_DATA_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    operateDataList: [],
    operateDataDataCount: null,
    operateDataPageSize: 20,
    operateDataHistoryData: [],
    row: {
      ctime: '',
      company: '',
      allcst: '',
      comecst: '',
      ordercst: ''
    }
  },
  getters: {
    operateDataList: state => state.operateDataList
  },
  mutations: {
    [OPERATE_DATA_LIST] (state, data) {
      state.operateDataList = data
    },
    [OPERATE_DATA_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [OPERATE_DATA_DATA_COUNT] (state, data) {
      state.operateDataDataCount = data
    },
    [OPERATE_DATA_HISTORY_DATA] (state, data) {
      state.operateDataHistoryData = data
    },
    [OPERATE_DATA_PAGE_SIZE] (state, data) {
      state.operateDataPageSize = data
    }
  },
  actions: {
    async getOperateDataList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getOperateDataTable(data)
      // console.log(resp)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          ctime: item.ctime,
          company: item.company,
          allcst: item.allcst,
          comecst: item.comecst,
          ordercst: item.ordercst
        }]
      })
      commit(OPERATE_DATA_LIST, newData)
      commit(OPERATE_DATA_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.operateData.operateDataPageSize) {
        commit(OPERATE_DATA_HISTORY_DATA, newData)
      } else {
        commit(OPERATE_DATA_HISTORY_DATA, newData.slice(0, rootState.operateData.operateDataPageSize))
      }
      return resp
    },
    async getOperateDataCurrentRow ({ commit, rootState }, row) {
      commit(OPERATE_DATA_CURRENT_ROW, row)
    },
    async changeOperateDataPage ({ commit, rootState }, index) {
      let data = rootState.operateData.operateDataList
      let _start = (index - 1) * rootState.operateData.operateDataPageSize
      let _end = index * rootState.operateData.operateDataPageSize
      commit(OPERATE_DATA_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeOperateDataPageSize ({ commit, rootState }, value) {
      commit(OPERATE_DATA_PAGE_SIZE, value)
    }
  }
}
